<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色功能区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCateDialogVisible = true; getParentCateList()">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 商品分类列表 -->
      <el-table
        :data="cateList"
        border
        stripe
        row-key="cat_id"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <!-- <el-table-column label="#" type="index"></el-table-column> -->
        <el-table-column label="分类名称" prop="cat_name"></el-table-column>
        <el-table-column label="是否有效" prop="cat_deleted">
          <template slot-scope="scope">
            <i v-if="scope.row.cat_deleted === false" class="el-icon-success" style="color: lightgreen; font-size:18px"></i>
            <i v-else class="el-icon-error" style="color: red; font-size:18px"></i>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="cat_level">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
            <el-tag type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
            <el-tag type="warning" v-else>三级</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="getCateInfoById(scope.row.cat_id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeCate(scope.row.cat_id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="this.queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.total">
      </el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed">
      <el-form :model="addCateForm" :rules="setCateRules"
      ref="addCateFormRef" label-width="80px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="selectedKeys"
            :options="parentCateList"
            expandTrigger="hover"
            :props="cascaderProps"
            @change="parentCateChange"
            clearable
            change-on-select>
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑分类对话栏 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="setCateDialogVisible"
      width="50%">
      <el-form :model="setCateForm" :rules="setCateRules" ref="setCateRef" label-width="80px">
        <el-form-item label="角色名称" prop="cate_name">
          <el-input v-model="setCateForm.cate_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setCateInfo">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 获取商品分类列表的参数对象
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 商品分类列表
      cateList: [],
      // 商品分类总条数
      total: 0,
      // 控制编辑分类对话框的显示与隐藏
      setCateDialogVisible: false,
      // 控制添加分类对话框的显示与隐藏
      addCateDialogVisible: false,
      // 添加分类对话框选中的父级分类id
      selectedCatePid: '',
      // 添加商品分类信息
      addCateForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      // 保存编辑分类对话框中的分类名称
      setCateForm: {
        cate_id: 0,
        cate_name: ''
      },
      // 父级分类列表
      parentCateList: [],
      // 级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 选中的父级分类id
      selectedKeys: [],
      setCateRules: {
        cate_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 8, message: '分类名称长度为1-8位字符', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获得当前商品分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('/categories', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败！')
      // console.log(res)
      this.cateList = res.data.result
      this.total = res.data.total
    },
    // 商品分类列表 当前页面单页数据条数变更
    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      this.getCateList()
    },
    // 商品分类列表 当前页面的页码数变更
    handleCurrentChange (val) {
      this.queryInfo.pagenum = val
      this.getCateList()
    },
    // 根据id获取分类信息
    async getCateInfoById (id) {
      const { data: res } = await this.$http.get(`/categories/${id}`)
      if (res.meta.status !== 200) return this.$message.error('分类信息获取失败！')
      this.setCateForm.cate_id = res.data.cat_id
      this.setCateForm.cate_name = res.data.cat_name
      this.setCateDialogVisible = true
    },
    // 编辑分类信息
    async setCateInfo () {
      const { data: res } = await this.$http.put(`categories/${this.setCateForm.cate_id}`, { cat_name: this.setCateForm.cate_name })
      if (res.meta.status !== 200) return this.$message.error('分类信息编辑失败！')
      this.$message.success('分类信息编辑成功！')
      this.setCateForm.cate_name = res.data.cat_name
      this.getCateList()
      this.setCateDialogVisible = false
    },
    // 获取所有父级分类列表
    async getParentCateList () {
      const { data: res } = await this.$http.get('/categories', { params: { type: 2 } })
      if (res.meta.status !== 200) return this.$message.error('获取父级分类列表失败！')
      this.parentCateList = res.data
    },
    parentCateChange () {
      if (this.selectedKeys.length > 0) {
        this.addCateForm.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ]
        this.addCateForm.cat_level = this.selectedKeys.length
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    addCate () {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return console.log('err')
        const { data: res } = await this.$http.post('/categories', this.addCateForm)
        if (res.meta.status !== 200) return this.$message.error('添加分类失败！')
        this.$message.success('添加分类成功！')
        this.getCateList()
        this.addCateDialogVisible = false
      })
    },
    addCateDialogClosed () {
      this.$refs.addCateFormRef.resetFields()
      this.selectedKeys = []
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_pid = 0
    },
    // 移除角色的权限
    async removeCate (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') return this.$message.info('取消删除！')
      const { data: res } = await this.$http.delete(`/categories/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除分类失败！')
      this.$message.success('删除分类成功！')
      this.getCateList()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-cascader {
  width: 100%
}
</style>
